

$(function(){    
    var isLogin = urls.checklogin();
    if(!isLogin) {
        $('.alert-title').html('未登录，请先登录');
        var $dialog = $('.modal-alert');
        $dialog.show();
        $dialog.find('.weui_btn_dialog').unbind('click').bind('click', function () {
            location.href = '../login';          
        });
        setTimeout(function(){
            location.href = '../login';
        }, 3000);
        return;
    }
    Page.token = urls.GetQueryString('t');
    $('.btn-cancel').attr('href', '../home?t=' + Page.token);
	Page.loadData();
	$('.select-brand').click(Page.showBrand);
    $('.select-cartype').click(Page.showTypes);
    $('.select-year').click(Page.showYears);
    $('.select-km').click(Page.showKM);
    $('.select-merchants').click(Page.showMerchants);
    $('.select-sale').click(Page.showSale);
    $('.select-location').click(Page.showLocation);
	$('.select-modal').click(Page.showModals);

    $('.btn-sure').click(Moto.add);

    $('.mask .backdrop').click(function(){        
        Page.hideDialog();
    });
    Page.id = urls.GetQueryString('key');
    if(Page.id != '') {
        Page.loadMoto();
    }
});

var Page = {};

Page.showDialog = function() {
    $('.mask, .mask .content').removeClass('hide').addClass('show');
    $('.wrapper').addClass('no-scrollbar');
}
Page.hideDialog = function() {
    $('.mask, .mask .content').removeClass('show').addClass('hide');
    $('.wrapper').removeClass('no-scrollbar');
}
Page.alert = function(string){
    $('.alert-title').html(string);
    var $dialog = $('.modal-alert');
    $dialog.show();
    $dialog.find('.weui_btn_dialog').unbind('click').bind('click', function () {
        $dialog.hide();
    });
}
Page.loadMoto = function() {
    var url = urls.server + '/bikes/' + Page.id;
    $.ajax({
        type: 'GET',
        async: true,
        url: url,
        dataType: 'json',
        data: {
            id: Page.id
        },
        success: function(e){
            if(e && e.id) {
                $('.select-brand').html(e.brand + '>>').attr({'data-brandid':e.brand_id,'data-brandname':e.brand});
                $('.select-cartype').html(e.category + '>>').attr({'data-cartypeid':e.category_id, 'data-cartypename':e.category});
                $('.select-year').html(e.year + '>>').attr('data-year', e.year);
                $('.select-km').html(e.real_km + '>>').attr('data-km', e.real_km);
                $('.select-sale').html( (e.sale_state == '0' ? '已售' : '在售' ) + '>>').attr('data-sale', e.sale_state);
                $('.select-location').html( e.site + '>>').attr('data-location', e.site);
                if(e.merchant && e.merchant.length > 0) {
                    $('.select-merchants').html( e.merchant[0].name + '>>').attr('data-id', e.merchant[0].number);
                }
                if(e.param_link_model && e.param_link_model.length > 0) {
                    $('.select-modal').html( e.param_link_model[0].name + '>>').attr('data-id', e.param_link_model[0].id);                    
                }

                $('.txt-name').val(e.name);
                $('.txt-price').val(e.price);
                $('.txt-min-price').val(e.min_price);
                $('.txt-displacement').val(e.displacement);
                $('.txt-view-change').val(e.view_change);
                $('.txt-diy').val(e.diy);


                // $('.select-merchants').html(e.real_km + '>>').attr('data-km', e.real_km);
            }
        }
    });
}

var Moto = {};
Moto.brands = [];
Moto.mcats = [];
Moto.kms = ['不限', '1万公里以下', '1万公里以上', '2万公里以上', '3万公里以上', '4万公里以上', '5万公里以上'];
Moto.sales = [
    {key: '1', value:'在售'},
    {key: '0', value:'已售'}
];
Moto.locations = ['碣石'];

Moto.verify = function() {

}
Moto.add = function() {
    var brand_id = $('.select-brand').attr('data-brandid');
    var brand_name = $('.select-brand').attr('data-brandname');
    if( !brand_id || brand_id == '-1' ) {
        Page.alert('请选择品牌');
        return;
    }

    var category_id = $('.select-cartype').attr('data-cartypeid');
    var category = $('.select-cartype').attr('data-cartypename');
    if(!category || category_id == '-1') {
        Page.alert('请选择类型');
        return;        
    }

    var year = $('.select-year').attr('data-year');
    if(!year) {
        Page.alert('请选择出厂年份');
        return;        
    }

    var name = $('.txt-name').val();
    if(name == '') {
        Page.alert('请输入名称');
        return;                
    }

    var real_km = $('.select-km').attr('data-km');
    if(!real_km) {
        Page.alert('请选择实际公里数');
        return;        
    }

    var price = $('.txt-price').val();
    if(price == '') {
        Page.alert('请输入售价');
        return;                
    }
    if(isNaN(Number(price)) || Number(price) < 0) {
        Page.alert('售价只能为正数');
        return;                   
    }
    var min_price = $('.txt-min-price').val();
    if(min_price == '') {
        Page.alert('请输入最低底价');
        return;                
    }
    if(isNaN(Number(min_price)) || Number(min_price) < 0) {
        Page.alert('最低底价只能为正数');
        return;                   
    }
    var displacement = $('.txt-displacement').val();
    if(displacement == '' ) {
        Page.alert('请输入排量');
        return;                
    }
    if(isNaN(Number(displacement)) || Number(displacement) < 0) {
        Page.alert('排量只能为正数');
        return;                   
    }

    var merchant_num = $('.select-merchants').attr('data-id');
    if(!merchant_num || merchant_num == '-1') {
        Page.alert('请选择商家');
        return;        
    }
    var sale_state = $('.select-sale').attr('data-sale');
    if(!sale_state) {
        Page.alert('请选择销售状态');
        return;        
    }

    var site = $('.select-location').attr('data-location');
    if(!site) {
        Page.alert('请选择车辆所在地');
        return;        
    }

    var view_change = $('.txt-view-change').val();
    var diy = $('.txt-diy').val();


    var param = {
        name: name,
        brand_id: brand_id,
        brand: brand_name,
        year: year,
        category: category,
        category_id: category_id,
        real_km: real_km,
        price: price,
        min_price: min_price,
        displacement: displacement,
        merchant_num: merchant_num,
        sale_state: sale_state,
        site: site,
        access_token: 'AABBCCDD'
    }

    if(view_change != '') {
        param.view_change = view_change;
    }
    if(diy != '') {
        param.diy = diy;
    }

    var param_link_model_id = $('.select-modal').attr('data-id');
    if(param_link_model_id) {
        param.param_link_model_id = param_link_model_id;
    }

    var url = urls.server + '/bikes';
    if(Page.id != '') {
        param.id = Page.id;
        url += '/' + Page.id;
    }
    param.access_token = 'AABBCCDD';

    $.ajax({
        type: (Page.id == '' ? 'POST' : 'PUT' ),
        async: true,
        url: url,
        dataType: 'json',
        data: param,
        success: function(e){
            if(e && e.id) {

                if(Page.id == '') {
                    $('.alert-title').html('添加成功');
                }
                else {
                    $('.alert-title').html('修改成功');
                }
                
                var $dialog = $('.modal-alert');
                $dialog.show();
                $dialog.find('.weui_btn_dialog').unbind('click').bind('click', function () {
                    location.href = "../home?t=" + Page.token;
                });
            }
        }
    });
}
Moto.modify = function() {

}

Page.showBrand = function(){
    Page.showDialog();

    $('.choice .content .title').html("品牌").attr('data-type', 'open-brand');

    var h = '<li class="action" data-type="brand" data-id="-1"><span>不限</span></li>';
    var brands = Moto.brands.concat();
    var len = brands.length;
    for(var i=0; i<len; i++) {
        var item = brands[i];
        h += '<li data-type="brand" data-id="'+ item.id +'"><a href="javascript:;"><span>'+ item.name +'</span></a></li>';
    }
    $('.choice .content .dialog').html(h);
    Page.bindChoiceClick();
}
Page.showTypes = function(){
    Page.showDialog();

    $('.choice .content .title').html("类型").attr('data-type', 'open-cartype');

    var h = '<li class="action" data-id="-1"><span>不限</span></li>';
    var data = Moto.mcats.concat();
    var len = data.length;
    for(var i=0; i<len; i++) {
        var item = data[i];
        h += '<li data-id="'+ item.id +'"><a href="javascript:;"><span>'+ item.nameCn +'</span></a></li>';
    }
    $('.choice .content .dialog').html(h);
    Page.bindChoiceClick();
}

Page.showYears = function() {
    Page.showDialog();
    var h = '';
    $('.choice .content .title').html("出厂年份").attr('data-type', 'open-year');
    for( var i=2016; i>1975; i-- ) {
        h += '<li><a href="javascript:;"><span>'+ i +'</span></a></li>';        
    }
    $('.choice .content .dialog').html(h);
    Page.bindChoiceClick();
}

Page.showModals = function() {    
    Page.showDialog();
    $('.modal-preloader').addClass('show').html('正在加载数据...');
    $('.choice .content .title').html("车型").attr('data-type', 'open-modal');
    $('.choice .content .dialog').html('<li class="action" data-id="-1"><span>不限</span></li>');

    var url = urls.server + '/models?limit=100&offset=0', param = {};

    var brand_id = $('.select-brand').attr('data-brandid');
    if( brand_id && brand_id != '-1' ) {
        // url += '&query=';
        // url += '["brand","'+ brand_id +'","="]';
        param.brand_id = brand_id;
    }
    var category_id = $('.select-cartype').attr('data-cartypeid');
    if(category_id && category_id != '-1') {
        // if(!url.match('&query=')) {
        //     url += '&query=';            
        // }
        // url += '["cat","'+ category_id +'","="]';   
        param.cat_id = category_id; 
    }

    var year = $('.select-year').attr('data-year');
    if(year) {
        // if(!url.match('&query=')) {
        //     url += '&query=';            
        // }
        // url += '["year","'+ year +'","="]';    
        param.year = year;            
    }

    var name = $('.txt-name').val();
    if(name != '') {
        // if(!url.match('&query=')) {
        //     url += '&query=';            
        // }
        // url += '["name_cn","'+ name +'","like"]';  
        param.name_cn = name.replace(/\s/ig,'');                                     
    }

    var h = '<li class="action" data-id="-1"><span>不限</span></li>';

     $.ajax({
        type: 'GET',
        async: true,
        url: url,
        dataType: 'json',
        data: param,
        success: function(e){
            if(e && e.length > 0) {
                var h = '';                
                for(var i=0, len=e.length; i<len; i++) {
                    var item = e[i];
                    h += '<li data-id="'+ item.id +'" data-brand="'+ item.brand +'" data-brand-id="'+ item.brand_id +'" data-cat="'+ item.cat +'" data-cat-id="'+ item.cat_id +'" data-name="'+ item.name +'"><a href="javascript:;"><span>'+ item.year + '款' + item.name +'</span></a></li>';
                }
                $('.choice .content .dialog').append(h);

                Page.bindChoiceClick();
                $('.modal-preloader').removeClass('show');
                /*return;

                if(e.length < 50) {
                    Modal.noMore = true;
                    $('.modal-preloader').addClass('show').html('没有更多数据了');
                }
                else {
                    Modal.skip += e.length;
                    $('.modal-preloader').removeClass('show');
                }*/
            }
            else {           
                $('.modal-preloader').html('查询到0条数据，请重新搜索');
            }

        }
    });
}

Page.showKM = function() {
    Page.showDialog();
    var len = Moto.kms.length;
    var h = '';
    $('.choice .content .title').html("实际公里数").attr('data-type', 'open-km');
    for( var i=0; i<len; i++ ) {
        var item = Moto.kms[i];
        h += '<li><a href="javascript:;"><span>'+ item +'</span></a></li>';        
    }
    $('.choice .content .dialog').html(h);
    Page.bindChoiceClick();
}

Page.showMerchants = function() {
    Page.showDialog();
    $('.choice .content .title').html("商家").attr('data-type', 'open-merchants');
    $('.choice .content .dialog').html('');
    $.ajax({
        type: 'GET',
        async: true,
        url: urls.server + '/merchants',
        dataType: 'json',
        success: function(e){
            if(e.length > 0) {                
                var h = '<li class="action" data-id="-1"><span>不限</span></li>';
                var len = e.length;
                for(var i=0; i<len; i++) {
                    var item = e[i];
                    h += '<li data-type="merchants" data-id="'+ item.number +'"><a href="javascript:;"><span>'+ item.name +'</span></a></li>';
                }
                $('.choice .content .dialog').html(h);
                Page.bindChoiceClick();
            }
        }
    });
}

Page.showSale = function() {
    Page.showDialog();
    var len = Moto.sales.length;
    var h = '';
    $('.choice .content .title').html("销售状态").attr('data-type', 'open-sale');
    for( var i=0; i<len; i++ ) {
        var item = Moto.sales[i];
        h += '<li data-value="'+ item.key +'"><a href="javascript:;"><span>'+ item.value +'</span></a></li>';        
    }
    $('.choice .content .dialog').html(h);
    Page.bindChoiceClick();
}
Page.showLocation = function() {
    Page.showDialog();
    var len = Moto.locations.length;
    var h = '';
    $('.choice .content .title').html("所在地").attr('data-type', 'open-location');
    for( var i=0; i<len; i++ ) {
        h += '<li><a href="javascript:;"><span>'+ Moto.locations[i] +'</span></a></li>';        
    }
    $('.choice .content .dialog').html(h);
    Page.bindChoiceClick();
}


Page.bindChoiceClick = function(){
    $('.choice .content .dialog li').unbind('click').bind('click', function(){
        var me = $(this);
        var type = $('.choice .content .title').attr('data-type');

        var span = me.find('span');
        var text = span.text();
        $('.' + type).find('.weui_cell_ft').html(text);

        if(type == 'open-brand') {
            var val = me.attr('data-id');
            if(val != '-1') {
                $('.select-brand').html(text + ' >>').attr({'data-brandid':val, 'data-brandname': text});
            }
        }
        else if(type == 'open-cartype') {
            var val = me.attr('data-id');
            $('.select-cartype').html(text + ' >>').attr({'data-cartypeid':val, 'data-cartypename': text});
        }
        else if( type == "open-year" ) {
            if(val != '-1') {
                $('.select-year').html(text + ' >>').attr('data-year', text);   
            }         
        }
        else if( type == "open-km" ) {
            $('.select-km').html(text + ' >>').attr('data-km', text);            
        }
        else if( type == "open-merchants" ) {
            var val = me.attr('data-id');
            if(val != '-1') {
                $('.select-merchants').html(text + ' >>').attr('data-id', val);
            }            
        }
        else if( type == "open-sale" ) {
            var val = me.attr('data-value');
            $('.select-sale').html(text + ' >>').attr('data-sale', val);            
        }
        else if( type == "open-location" ) {
            $('.select-location').html(text + ' >>').attr('data-location', text);            
        }
        else if( type == "open-modal" ) {
            var val = me.attr('data-id');
            if(val != '-1') {
                $('.select-modal').html(text + ' >>').attr('data-id', val);
                if( !$('.select-brand').attr('data-brandid') ) {
                    $('.select-brand').html(me.attr('data-brand') + ' >>').attr({'data-brandid':me.attr('data-brand-id'), 'data-brandname': me.attr('data-brand')});
                }
                if( !$('.select-cartype').attr('data-cartypeid') ) {
                    $('.select-cartype').html(me.attr('data-cat') + ' >>').attr({'data-cartypename':me.attr('data-cat'), 'data-cartypeid': me.attr('data-cat-id')});
                }
                if( $('.txt-displacement').val() == '' ) {
                    Page.setDisplacement(val);
                }
                $('.txt-name').val(me.attr('data-name'));
            }                       
        }

        Page.hideDialog();
    });
}

Page.setDisplacement = function(modelId) {
    $.ajax({
        type: 'GET',
        async: true,
        url: urls.server + '/models/'+ modelId +'/mdetails',
        data: {
            id: modelId
        },
        dataType: 'json',
        success: function(e){
            if(e && e.length > 0) {
                for(var i=0, len=e.length; i<len; i++) {
                    var item = e[i];
                    if( item.mtitle === "引擎和传动" ) {
                        for( var k=0, ll=item.sub_param.length; k<ll; k++) {
                            var m = item.sub_param[k];
                            if(m.item_cn="排量") {
                                var str = m.item_value;
                                str = str.split(' ccm')[0];
                                $('.txt-displacement').val(str)
                                break;
                            }
                        } 
                        break;
                    }
                }
                
            }
        }
    });
}


Page.loadData = function() {
    Moto.loadBrands();
    Moto.loadMcats();
}

/**
 * 查询所有品牌
 */
Moto.loadBrands = function() {
    $.ajax({
        type: 'GET',
        async: true,
        url: urls.server_v1 + '/MotoBrands?filter[fields][id]=true&filter[fields][name]=true',
        dataType: 'json',
        success: function(e){
            if(e && e.length > 0) {
                Moto.brands = e.concat();
            }
            else {
                Moto.brands = [];
            }
        }
    });
}


/**
 * 查询所有类型
 */
Moto.loadMcats = function() {      
    $.ajax({
        type: 'GET',
        async: true,
        url: urls.server_v1 + '/MotoMcats?filter[fields][id]=true&filter[fields][nameCn]=true',
        dataType: 'json',
        success: function(e){
            if(e && e.length > 0) {
                Moto.mcats = e.concat();
            }
            else {
                Moto.mcats = [];
            }
        }
    });
}
